package com.gonsin.gview.logic.validate;

import com.gonsin.gview.logic.exceptions.BaseGViewException;
import com.gonsin.gview.model.GButtonModel;
import com.gonsin.gview.model.GPropModel;
import com.gonsin.gview.model.GViewModel;
import com.gonsin.gview.model.form.GFormBoardModel;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 针对View的格式校验
 */
public class ViewValidate implements IModelValidate<GViewModel>{


    @Override
    public void validate(ValidateContext context, GViewModel view) {
        if(CollectionUtils.isEmpty(view.getProps())){
            return;
        }
        // 查询所有打开该view的button
        List<GButtonModel> buttons = context.getCoreService().findButtonByView(view.getViewName());
        if(CollectionUtils.isEmpty(buttons)){
            return;
        }
        for(GButtonModel b : buttons){
            if(containAll(b.getProps(), view.getProps())){
                continue;
            }
            throw new BaseGViewException(String.format("【%s】中@GButton需要打开view【%s】，但是【%s】需要传递props=【%s】，" +
                            "请在@GButton中添加 props 表示需要传递的参数",
                    b.getContext().getViewName(), view.getViewName(), view.getViewName(), Arrays.toString(view.getProps().toArray())));
        }

    }

    /**
     * 按钮跳转的参数，是否包含了跳转需要的参数
     */
    private boolean containAll(List<GPropModel> buttons, List<String> viewProps) {
        List<String> buttonProps = buttons.stream().map(b -> b.getKeyName()).collect(Collectors.toList());
        return new HashSet<>(buttonProps).containsAll(viewProps);
    }
}
